package com.lsy.weizhi2.utils;

import android.content.Context;
import android.os.Handler;
import android.util.Log;

import com.lsy.weizhi2.JsonObject.LoginObject;
import com.lsy.weizhi2.config.Constants;
import com.lsy.weizhi2.config.MyInfo;
import com.lsy.weizhi2.mybase.BaseApp;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by 嗨哟 on 2016/12/12.
 */
public class MyOkHttpUtils {

    static OkHttpClient client =new OkHttpClient.Builder().connectTimeout(5, TimeUnit.SECONDS).build();
    MultipartBody.Builder multi_builder;
    MediaType MEDIATYPE_JSON = MediaType.parse("application/x-www-form-urlencoded");
    MediaType MEDIATYPE_UP= MediaType.parse("text/x-markdown");
    Request.Builder builder;
    private static MyOkHttpUtils utils;
    private Context context;

    private MyOkHttpUtils(Context context) {
        this.context=context;
    }

    public static MyOkHttpUtils getInstance(Context context) {
        if (utils == null) {
            utils = new MyOkHttpUtils(context);
        }
        return utils;
    }

    /**
     * 做GET请求
     *
     * @param url   不带参数的 请求地址
     * @param pairs 参数列表
     * @return
     */
    public MyOkHttpUtils doGet(String url, Map<String, String> pairs) {
        builder = new Request.Builder();
        if(pairs!=null&&pairs.size()!=0){
            url=url+buildGetUrlOrder(pairs);
        }
        builder.url(url).addHeader("WZ-AUTH-TOKEN",MyInfo.Token).addHeader("WZ-AUTH-ID",MyInfo.User_Id+"");
        return utils;
    }

    public MyOkHttpUtils doPut(String url, Map<String, String> map){
        builder = new Request.Builder();
        FormBody.Builder builder_f=new FormBody.Builder();
        RequestBody requestBody = null;
        if(map!=null&&map.size()!=0){
            for (String key:map.keySet()) {
                if(map.get(key)==null){
                    builder_f.add(key,"");
                }else{
                    builder_f.add(key,map.get(key));
                }
            }
            requestBody = builder_f.build();
        }else{
            requestBody = okhttp3.internal.Util.EMPTY_REQUEST;
        }
        Log.i("MyOkHttp","requestBody=="+requestBody);
        builder.url(url).put(requestBody).addHeader("WZ-AUTH-TOKEN",MyInfo.Token).addHeader("WZ-AUTH-ID",MyInfo.User_Id+"");
        return utils;
    }

    /**
     * 登录专用
     * @param url
     * @param map 参数
     * @return
     */
    public MyOkHttpUtils doPostLogin(String url, Map<String,String>map) {
        builder = new Request.Builder();
        FormBody.Builder builder_f=new FormBody.Builder();
        for (String key:map.keySet()) {
            builder_f.add(key,map.get(key));
        }
        RequestBody requestBody= builder_f.build();
        builder.url(url).post(requestBody);
        return utils;
    }

    /**
     * 非登录全部带token和id
     * @param url
     * @param map 参数
     * @return
     */
    public MyOkHttpUtils doPost(String url, Map<String,String>map){
        builder = new Request.Builder();
        FormBody.Builder builder_f=new FormBody.Builder();
        if(map!=null&&map.size()!=0){
            for (String key:map.keySet()) {
               if(map.get(key)==null){
                   builder_f.add(key,"");
               }else{
                   builder_f.add(key,map.get(key));
               }
            }
        }

        RequestBody requestBody= builder_f.build();
        builder.url(url).post(requestBody).addHeader("WZ-AUTH-TOKEN",MyInfo.Token).addHeader("WZ-AUTH-ID",MyInfo.User_Id+"");
        return utils;
    }
    /**
     * 注册发送验证码不带
     */
    public MyOkHttpUtils doPostSMS(String url, Map<String,String>map){
        builder = new Request.Builder();
        FormBody.Builder builder_f=new FormBody.Builder();
        if(map!=null&&map.size()!=0){
            for (String key:map.keySet()) {
                if(map.get(key)==null){
                    builder_f.add(key,"");
                }else{
                    builder_f.add(key,map.get(key));
                }
            }
        }

        RequestBody requestBody= builder_f.build();
        builder.url(url).post(requestBody);
        return utils;
    }
    /**
     * 做用户登出 请求
     *
     * @param url   不带参数的url
     * @return
     */
    public MyOkHttpUtils doDetele(String url){
        builder = new Request.Builder();
        builder.url(url).addHeader("WZ-AUTH-TOKEN",MyInfo.Token).addHeader("WZ-AUTH-ID",MyInfo.User_Id+"").delete();
        return utils;
    }
    /**
     * 图片上传（通过File 形式 eg.<input type="file" name="nFime"/> ）
     *
     * @param url   接口地址
     * @param file  文件绝对地址（包含图片名称）
     * @return
     */
    public MyOkHttpUtils upLoadImage(String url, File file) {
        builder = new Request.Builder();
        Log.i("Okhttp","Type=="+getMimeType(file.getName()));
        RequestBody requestBody1= RequestBody.create(MediaType.parse(getMimeType(file.getName())),file);
        //分块请求构建RequestBody
        RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("image",file.getName(),requestBody1).build();
        Log.i("Okhttp","TOKEN==="+MyInfo.Token);
        builder.url(url).post(requestBody).addHeader("WZ-AUTH-TOKEN",MyInfo.Token).addHeader("WZ-AUTH-ID",MyInfo.User_Id+"").addHeader("enctype","multipart/form-data");
        return utils;
    }

    Handler handler = new Handler();
    /**
     * 执行最后的请求操作
     *
     * @param back 回调（该操作已经在主线程里）
     */
    public void excute(final OKCallBack back) {
        if(MyMethod.isNetworkConnected(BaseApp.context)){
            client.newCall(builder.build()).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    if (back != null) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                back.onFailure("获取网络数据失败");
                            }
                        });
                    }
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    final String result = response.body().string();
                    if (back != null) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                if (!(result.equals(""))) {
                                    back.onResponse(result);
                                }
                            }
                        });

                    }
                }
            });
        }else{
            MyMethod.ShowDialogNet(context);
        }

    }

    public void excute_image(final OKCallBack2 back){
        client.newCall(builder.build()).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (back != null) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            back.onFailure("获取网络数据失败");
                        }
                    });
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final byte[]bytes=response.body().bytes();
                if (back != null) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (!(bytes.equals(""))) {
                                back.onImage(bytes);
                            }
                        }
                    });

                }
            }
        });
    }

    private static  String getMimeType(String filename){
        FileNameMap fileNameMap= URLConnection.getFileNameMap();
        String contentTypeFor=fileNameMap.getContentTypeFor(filename);
        if(contentTypeFor==null){
            contentTypeFor="application/octet-stream";
        }
        return contentTypeFor;
    }
    private String buildGetUrlOrder(Map<String, String> pairs){
        if (pairs != null && !pairs.isEmpty()) {
            boolean isFirst = true;
            StringBuilder sb = new StringBuilder();
            for (String key : pairs.keySet()) {
                String value = pairs.get(key);
                if (isFirst) {
                    sb.append("?");
                    isFirst = false;
                } else {
                    sb.append("&");
                }
                sb.append(key);
                sb.append("=");
                sb.append(value);
            }
            return sb.toString();
        }
        return "";
    }

    private String buildGetUrl(Map<String, String> pairs) {
        if (pairs != null && !pairs.isEmpty()) {
            boolean isFirst = true;
            StringBuilder sb = new StringBuilder();
            for (String key : pairs.keySet()) {
                String value = pairs.get(key);
                if (isFirst) {
                    sb.append("?");
                    isFirst = false;
                } else {
                    sb.append("&");
                }
                sb.append(key);
                sb.append("=");
                sb.append(value);
            }
            return sb.toString();
        }
        return "";
    }
    public interface LoginOkCallBack{
        void onFailure(String message);
        void getToken(String token);
        void onResponse(String message);
    }
    public interface OKCallBack {
        void onFailure(String message);
        void onResponse(String message);
    }
    public interface OKCallBack2 {
        void onFailure(String message);
        void onResponse(String message);
        void onImage(byte[] bytes);
    }
}
